package com.wuyangnju.healthclub.controller;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.wuyangnju.healthclub.entity.Child;
import com.wuyangnju.healthclub.entity.Family;
import com.wuyangnju.healthclub.entity.Husband;
import com.wuyangnju.healthclub.entity.Person;
import com.wuyangnju.healthclub.entity.Wife;
import com.wuyangnju.healthclub.service.FamilyService;
import com.wuyangnju.healthclub.service.PersonService;

@Controller
public class FamilyController {

	@Resource
	PersonService personService;

	@Resource
	FamilyService familyService;

	@RequestMapping(value = { "/resource/families.delete" })
	public ModelAndView delete(@RequestParam String cardId) {
		Family family = familyService.get(cardId);
		familyService.delete(family);
		return new ModelAndView(
				new RedirectView("/resource/families.get", true));
	}

	@RequestMapping(value = { "/resource/families.get" })
	public ModelAndView get() {
		return new ModelAndView("family", "families", familyService.get());
	}

	@RequestMapping(value = { "/resource/families.put" })
	public ModelAndView put(@RequestParam String cardId,
			@RequestParam String husbandName, @RequestParam int husbandAge,
			@RequestParam String wifeName, @RequestParam int wifeAge,
			@RequestParam String childName, @RequestParam int childAge,
			@RequestParam String childSex, @RequestParam String address) {

		if (("".equals(cardId)) || (cardId == null)) {
			Husband husband = new Husband(husbandName, husbandAge, address);
			personService.post(husband);

			Wife wife = new Wife(wifeName, wifeAge, address);
			personService.post(wife);

			Child child = new Child(childName, "male", childAge, address);
			personService.post(child);

			Set<Person> members = new HashSet<Person>();
			members.add(husband);
			members.add(wife);
			members.add(child);
			Family family = new Family(members);
			familyService.post(family);

		} else {
			Family family = familyService.get(cardId);
			Husband husband = family.getHusband();
			Wife wife = family.getWife();
			Child child = family.getChild();

			husband.setAge(husbandAge);
			husband.setName(husbandName);
			husband.setAddress(address);

			wife.setAge(wifeAge);
			wife.setName(wifeName);
			wife.setAddress(address);

			child.setAge(childAge);
			child.setName(childName);
			child.setSex(childSex);
			child.setAddress(address);

			familyService.put(family);
		}

		return new ModelAndView(
				new RedirectView("/resource/families.get", true));
	}
}